<template>
  <div id="blog"
       style="overflow: auto"
       v-wechat-title="articleInfo.title"
       v-infinite-scroll="handleInfinite"
       :infinite-scroll-delay="300"
       :infinite-scroll-disabled="disabled">
    <el-dialog :visible.sync="dialogPictureVisible" fullscreen style="text-align: center">
      <img :src="dialogImageUrl" alt="dialogImageUrl" style="margin: 0 auto;"/>
    </el-dialog>
    <div class="blog-container">
      <div class="blog-box">
        <el-card style="padding: 10px">
          <span class="title-article">{{ articleInfo.title }}</span>
          <div class="article-info-box">
            <span class="article-info-author">
              <i class="el-icon-user"></i>
              {{ articleInfo.author }}
            </span>
            <span class="article-info-time">
              <i class="el-icon-time"></i>
              {{ articleInfo.createTime }}
            </span>
            <span class="article-info-time" style="margin-left: 12px;">
              <i class="el-icon-view"></i>
              阅读
              {{ articleInfo.clickNum }}
            </span>
            <span class="article-info-time" style="margin-left: 12px;">
              <i class="el-icon-chat-line-square"></i>
              评论
              {{ total }}
            </span>
            <div style="margin: 10px auto auto 20px">
            <span class="article-info-time"
                  v-if="articleInfo.categoryName !== undefined && articleInfo.categoryName.length > 0">
              文章分类：
              <el-button size="mini" type="primary" round plain>{{ articleInfo.categoryName }}</el-button>
            </span>

              <span class="article-info-time" style="margin-left: 12px;"
                    v-if="articleInfo.tagsName !== undefined && articleInfo.tagsName.length > 0">
              标签：
              <el-button v-for="(item,index) in articleInfo.tagsName"
                         :key="index"
                         size="mini"
                         type="primary"
                         round
                         plain>
                {{ item }}
              </el-button>
            </span>
            </div>
          </div>

          <el-divider></el-divider>
          <div class="me-view-content">
            <div id="content" class="markdown-body" v-html="articleInfo.content" v-highlight @click="imageChange">
            </div>
          </div>

          <div v-if="articleInfo.isComment === 1">
            <div class="container">
              <el-divider><span style="font-size: 20px; color: rgba(149,131,131,0.96) ">评论区</span></el-divider>
              <CommentBox :current-page="currentPage" :page-size="pageSize"></CommentBox>
              <CommentList :comment-list="commentList" :current-page="currentPage" :page-size="pageSize"></CommentList>
              <div class="noComment" v-if="commentList.length ==0">还没有评论，快来抢沙发吧！</div>
            </div>
            <div class="loading-container" v-if="this.loading">
              <svg class="spinner" width="35px" height="35px" viewBox="0 0 66 66" xmlns="http://www.w3.org/2000/svg">
                <circle class="path" fill="none" stroke-width="6" stroke-linecap="round" cx="33" cy="33"
                        r="30"></circle>
              </svg>
            </div>
          </div>
          <div style="margin-top: 45px" v-else>
            <el-divider><span style="font-size: 20px; color: rgba(149,131,131,0.96) ">本篇博文关闭评论功能</span></el-divider>
          </div>
        </el-card>
      </div>
      <div style="margin-top: 32px">
        <div class="catalog-box" v-if="navList.length != 0">
          <div class="catalog-title">目录</div>
          <el-tabs @tab-click="handleClick" v-model="activeName" :tab-position="tabPosition"
                   class="catalog-body">
            <el-tab-pane :name="'tab'+index"
                         :class="item.lev"
                         v-for="(item, index) in navList"
                         :key="index"
                         :label="item.name"></el-tab-pane>
          </el-tabs>
        </div>
      </div>
    </div>
    <el-tooltip placement="top" content="回到顶部">
      <back-to-top :document-id="'blog'"
                   :visibility-height="300"
                   :back-position="50"
                   @stopTagScroll="stopTagScroll"
                   transition-name="fade"/>
    </el-tooltip>
  </div>
</template>

<script>
import {mapGetters} from "vuex";
import CommentBox from '@/components/Comment/CommentBox'
import CommentList from '@/components/Comment/CommentList'
import 'github-markdown-css/github-markdown.css' // 添加样式markdown-body
import 'highlight.js/styles/github-gist.css';
import {getBlogInfo} from "@/api/blog";
import {getCommentById} from '@/api/comment'
import BackToTop from '@/components/BackToTop'

export default {
  name: "Blog",
  components: {CommentBox, CommentList, BackToTop},
  computed: {
    ...mapGetters(['comment', 'userInfo']),
    commentList: {
      get() {
        return this.comment
      },
      set() {
      }
    },
    noMore() {
      return this.currentPage * this.pageSize >= this.total
    },
    disabled() {
      return (this.loading || this.noMore) && this.articleInfo.isComment === 1
    }
  },
  data() {
    return {
      id: '',
      articleInfo: {},
      activeName: 'tab0',
      tabPosition: 'right',
      navList: [],
      currentPage: 1,
      pageSize: 10, //后台默认10
      total: 0,
      loading: false,
      dialogPictureVisible: false,
      isMoving: true,
      isScrollMoving: false,
      dialogImageUrl: [],
      tagScroll: [],
      moveTop: true
    }
  },
  methods: {
    selectBlogById(id) {
      let that = this
      getBlogInfo(id).then(res => {
        if (res.status) {
          that.articleInfo = res.data
        } else {
          this.$message.error(res.msg)
        }
      }).then(() => {
        setTimeout(() => {
          this.selectAllTitle()
        }, 100)

        setTimeout(() => {
          this.titleClass()
          document.getElementById("blog").scrollTop = 0
        }, 200)
      })
    },
    handleInfinite() {
      ++this.currentPage
      this.getCommentById()
    },
    getCommentById() {
      this.loading = true
      getCommentById(this.$route.params.bId, this.currentPage, this.pageSize).then(res => {
        let items = res.data.page;
        items.forEach(item => this.commentList.push(item))
        this.total = res.data.total
        this.$store.commit('SET_COMMENT_LIST', this.commentList)
        this.loading = false
      })
    },
    handleClick(tab, event) {
      this.isMoving = false
      let selectors = "#heading-" + tab.index
      document.querySelector(selectors).scrollIntoView({
        behavior: "smooth",  // 平滑过渡
        block: "start"
      });
      setTimeout(() => {
        this.isMoving = true
      }, 1000)
    },
    //根据标题获取生成目录
    selectAllTitle() {
      let title = document.getElementById('blog').querySelectorAll("h1,h2,h3,h4,h5,h6");
      title.forEach(item => {
        this.tagScroll.push(item.offsetTop - 60)
      })
      this.navList = Array.from(title);
      this.navList.forEach(item => {
        item.name = item.innerText;
      })
      this.navList.forEach(el => {
        let index = el.localName.indexOf('h');
        el.lev = 'lev' + el.localName.substring(index + 1, el.localName.length)
      });
    },
    //修改目录的样式
    titleClass() {
      let navs = document.querySelectorAll('.el-tabs__item');
      for (let i = navs.length - 1; i >= 0; i--) {
        // 从lev1到lev5分别添加不同到样式
        document.querySelector('#' + navs[i].id).style.padding = "0";
        if (this.navList[i].lev == 'lev1') {
          document.querySelector('#' + navs[i].id).style.paddingLeft = "20px";
        } else if (this.navList[i].lev == 'lev2') {
          document.querySelector('#' + navs[i].id).style.paddingLeft = "35px";
        } else if (this.navList[i].lev == 'lev3') {
          document.querySelector('#' + navs[i].id).style.paddingLeft = "50px";
        } else if (this.navList[i].lev == 'lev4') {
          document.querySelector('#' + navs[i].id).style.paddingLeft = "65px";
          document.querySelector('#' + navs[i].id).style.fontWeight = "400";
        } else if (this.navList[i].lev == 'lev5') {
          document.querySelector('#' + navs[i].id).style.paddingLeft = "80px";
          document.querySelector('#' + navs[i].id).style.fontWeight = "400";
        }
      }
    },
    imageChange: function (e) {
      //首先需要判断点击的是否是图片
      let type = e.target.localName;
      if (type == "img") {
        this.dialogPictureVisible = true;
        this.dialogImageUrl = e.target.currentSrc;
      }
    },
    handleScroll() {
      setTimeout(() => {
        if (this.isMoving) {
          let scrollTop = document.getElementById("blog").scrollTop;
          let tagScroll = this.tagScroll;
          for (let i = 0; i < tagScroll.length; i++) {
            //移动到了最后一个tab
            if (!tagScroll[i + 1]) {
              this.activeName = 'tab' + (tagScroll.length - 1);
              setTimeout(() => {
                document.getElementById('blog').getElementsByClassName("catalog-body")[0].scrollTop = (tagScroll.length - 1) * 40;
              }, 200);
              return;
            }
            if (tagScroll[i + 1] > scrollTop) {
              this.activeName = 'tab' + i;
              setTimeout(() => {
                document.getElementById('blog').getElementsByClassName("catalog-body")[0].scrollTop = i * 40;
              }, 200);
              return;
            }
          }
        }
      }, 500)

    },
    stopTagScroll(flag) {
      if (flag === 'true') {
        this.isMoving = true;
      } else {
        this.isMoving = false;
      }
      this.activeName = 'tab0';
    }
  },
  mounted() {
    document.getElementById("blog").addEventListener('scroll', this.handleScroll)
  },
  created() {
    this.$store.commit('SET_COMMENT_LIST', [])
    this.selectBlogById(this.$route.params.bId)
    this.getCommentById(this.$route.params.bId)
  },
  beforeRouteUpdate(to, from, next) {
    // 在当前路由改变，但是该组件被复用时调用
    // 举例来说，对于
    // /foo/:id，在 /foo/1 和 /foo/2 之间跳转的时候，
    // 由于会渲染同样的 Foo 组件，因此组件实例会被复用。而这个钩子就会在这个情况下被调用。
    this.selectBlogById(to.params.bId)
    this.getCommentById(to.params.bId)
    next()
  },
}
</script>

<style>

</style>
